import streamlit as st
import requests
import pandas as pd
import numpy as np
st.header("Matplotlib chart in Plotly")

import matplotlib.pyplot as plt

# f = plt.figure()
# arr = np.random.normal(1, 1, size=100)
# plt.hist(arr, bins=20)
#
# st.plotly_chart(f)

st.title("计算器")
choices = st.multiselect("what do u want?",["a","b","c","d"])

d_  = {'a':1,'b':2,'c':3,'d':4}

st.text('answer')
st.write('{}'.format(sum([d_[u] for u in choices])))
@st.cache
def api_get_position(code):
    url = f'https://api.doctorxiong.club/v1/fund/position?code={code}'
    res = requests.get(url)
    return res.json()

hot = 'https://api.doctorxiong.club/v1/fund/hot'
@st.cache
def api_hot_fund():
    url =hot
    res = requests.get(url)
    return res.json()

g = 'https://api.doctorxiong.club/v1/stock/board'
@st.cache
def api_get_board(g):
    url =g
    res = requests.get(url)
    return res.json()



yes = st.button('大盘')
if yes:
    res_board = api_get_board(g)
    st.text('大盘')
    #st.write(res_board)
    #st.write(hots['data']['rank'])
    cols = res_board['data'][0].keys()
    data = [[u[c] for c in cols]  for u in res_board['data']]
    data = sorted(data,key=lambda x:x[4],reverse=True)
    df = pd.DataFrame(data, columns=cols)
    st.dataframe(df, width=800)


hots = api_hot_fund()
all_funds = hots['data']['rank']
st.text('热门基金')
#st.write(hots['data']['rank'])
cols = ['code','name','fundType']
data = [[u[c] for c in cols]  for u in all_funds]

df = pd.DataFrame(data, columns=cols)
st.dataframe(df, width=800)

code = st.text_input("输入基金代码：")
if code != '':
    res = api_get_position(code)
    st.text("持仓是")
    #st.write(res)
    df = pd.DataFrame(res['data']['stockList'],columns="股票代码,名称,占比,持有股数(万股),持有金额(万元)".split(','))
    st.dataframe(df,width=600)

@st.cache
def history(code,start,end):
    url = 'https://q.stock.sohu.com/hisHq?code=cn_{}&start={}&end={}'

    rsp = requests.get(url.format(code,start,end))
    #print(url.format(code,start,end))
    #print(rsp.json())
    if isinstance(rsp.json(),dict):
        return []
    if 'hq' not in rsp.json()[0]:
        return []
    datas = rsp.json()[0]['hq']
    """
    日期,
    今日开盘价,
    今日收盘价,
    涨跌幅度，
    涨跌百分比,
    今日最低价,
    今日最高价，
    今日成交股票手数,
    今日成交金额(单位：万)
    换手率
    """
    return datas

code2 = st.text_input("输入股票代码：")
start = st.text_input("start：20210701")
end = st.text_input("end：")
if code2 != '':
    res = history(code2,start,end)
    st.text("持仓是")
    st.write(res)


